<template>
    <div class="eQuill">
        <quill-editor
            class="ql-editor"
            v-model="content"
            ref="myQuillEditor"
            :options="editorOption"
            style="padding:10px;"
            @scroll="scrollEvent"
            >
        </quill-editor>
    </div>
</template>
<script>
import Video from '@/units/quillVideo' //引用自定义的video
Quill.register(Video, true) //引用自定义的video
import { quillEditor } from 'vue-quill-editor' // 调用富文本编辑器
import { uploadFileApi } from "@/request/api" // 调用富文本编辑器
import 'quill/dist/quill.snow.css' // 富文本编辑器外部引用样式  三种样式三选一引入即可
import * as Quill from 'quill'; // 富文本基于quill
import ImageResize from 'quill-image-resize-module'; //引用图片可以放大缩小的插件
import {ImageDrop} from 'quill-image-drop-module'; //引用图片可拉拽的插件
Quill.register('modules/imageResize', ImageResize);
Quill.default.register("modules/imageDrop", ImageDrop);
//quill编辑器的字体
let fonts = ['SimSun', 'SimHei','Microsoft-YaHei','KaiTi','FangSong','Arial','Times-New-Roman','sans-serif'];  
let Font = Quill.import('formats/font');  
Font.whitelist = fonts; //将字体加入到白名单 
Quill.register(Font, true);

const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    ['blockquote', 'code-block'],
    [{'header': 1}, {'header': 2}],               // custom button values
    [{'list': 'ordered'}, {'list': 'bullet'}],
    // [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
    [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
    [{'direction': 'rtl'}],                         // text direction

    [{'size': ['12px', '14px', '16px' ,'18px', '20px', '22px', '24px', '26px', '32px', '48px']}],  // custom dropdown
    [{'header': [1, 2, 3, 4, 5, 6, false]}],

    [{'color': []}],
    [{'background': []}],          // dropdown with defaults from theme
    [{'font': fonts }],
    [{'align': []}],
    ['link', 'image','video'],
    ['clean']                                         // remove formatting button
]
const titleConfig = {
      "ql-bold": "加粗" ,
      "ql-color": "文本颜色",
      "ql-font": "字体",
      "ql-code": "插入代码",
      "ql-italic": "斜体",
      "ql-link": "添加链接",
      "ql-background": "背景颜色",
      "ql-size": "字号",
      "ql-strike": "删除线",
      "ql-script": "上标/下标",
      "ql-underline": "下划线",
      "ql-blockquote": "引用",
      "ql-header": "标题",
      "ql-indent": "缩进",
      "ql-list": "列表",
      "ql-align": "文本对齐",
      "ql-direction": "文本方向",
      "ql-code-block": "代码块",
      "ql-formula": "公式",
      "ql-image": "图片",
      "ql-video": "视频",
      "ql-clean": "清除字体样式",
      "ql-upload": "文件"
    };
export default {
    name:'eQuill',
    props:{defaultData:String},
    mounted(){
        this.content=this.defaultData
        this.editor = this.$refs.myQuillEditor.quill;
        let toolbar = this.editor.getModule('toolbar');
        this.$nextTick(() => {
            let arr=document.querySelector(".ql-editor .ql-editor")
            arr.addEventListener('scroll', this.scrollEvent)
        })
        this.addQuillTitle()
        let upload=(accept,className,type)=>{
            let fileInput = toolbar.container.querySelector('input.ql-image[type=file]');
            if (fileInput == null) {
                fileInput = document.createElement('input');
                fileInput.setAttribute('type', 'file');
                fileInput.setAttribute('accept', accept);
                fileInput.classList.add(className);
                fileInput.addEventListener('change',  () => {
                    if (fileInput.files != null && fileInput.files[0] != null) {
                        let formData=new FormData()
                        formData.append('file',fileInput.files[0])
                        this.getToken(uploadFileApi,formData,res=>{
                            if(res.data.imgUrl.length>0){
                                this.uploadImg=res.data.imgUrl[0]
                            }else if(res.data.videoUrl.length>0){
                                this.uploadImg=res.data.videoUrl[0]
                            }
                            let length = this.$refs.myQuillEditor.quill.selection.savedRange.index;
                            this.editor.insertEmbed(length, type, this.uploadImg)
                            this.editor.setSelection(length + 1)
                        })
                    }
                });
            }
            fileInput.click();
        }
        toolbar.addHandler('image', () => {
            upload('image/png, image/gif, image/jpeg, image/bmp, image/x-icon','ql-image','image')
        })
        toolbar.addHandler('video', () => {
            upload('audio/mp4, video/mp4','ql-video','video')
        })
    },
    watch:{
        content:function(val){
            this.$emit('getQuillContent',val.trim())
        }
    },
    components:{quillEditor},
    data(){
        return{
            content:'',
            imageUrl: '',
            uploadImg:'',
            apiUrl:window.g.apiUrl,
            editorOption: {    
                placeholder: "请在这里输入",            
                modules: {
                    imageDrop: true,
                    toolbar: {
                        container: toolbarOptions,  // 工具栏
                    },
                    imageResize: {
                        displayStyles: {
                            backgroundColor: "black",
                            border: "none",
                            color: "white"
                        },
                        modules: ["Resize", "DisplaySize"]
                    },
                }
            }
        }
    },
    methods:{
        addQuillTitle() {
            const oToolBar = document.querySelector(".ql-toolbar"),
            aButton = oToolBar.querySelectorAll("button"),
            aSelect = oToolBar.querySelectorAll("select");
            aButton.forEach(function(item) {
            if (item.className === "ql-script") {
                item.value === "sub" ? (item.title = "下标") : (item.title = "上标");
            } else if (item.className === "ql-indent") {
                item.value === "+1"
                ? (item.title = "向右缩进")
                : (item.title = "向左缩进");
            } else {
                item.title = titleConfig[item.classList[0]];
                }
            });
            aSelect.forEach(function(item) {
            item.parentNode.title = titleConfig[item.classList[0]];
            });
        },
        scrollEvent(){
            this.editor.getModule('imageResize').hide()
        }
    }
}
</script>
<style lang="stylus">
#app
    .ql-container
        padding:10px;
        .ql-editor 
            height:500px;
            overflow-y:auto;
            .ql-video
                width:60%;
    .ql-container.ql-snow
        overflow:hidden;
</style>